package top.zhangjianyong.utils.coding;


/**
 * @program: topzhangjianyongutils
 * @description: ASCII码工具类
 * @author: 张建勇
 * @create: 2019-03-15 09:00
 **/
public class UnicodeUtil {

    /**
     * 字符串转换unicode
     *
     * @param string
     * @return
     */
    public static String string2Unicode(String string) {
        StringBuffer unicode = new StringBuffer();
        for (int i = 0; i < string.length(); i++) {
            // 取出每一个字符
            char c = string.charAt(i);
            // 转换为unicode
            unicode.append("\\u" + Integer.toHexString(c));
        }

        return unicode.toString();
    }

    /**
     * unicode 转字符串
     *
     * @param unicode 全为 Unicode 的字符串
     * @return
     */
    public static String unicode2String(String unicode) {
        StringBuffer string = new StringBuffer();
        String[] hex = unicode.split("\\\\u");

        for (int i = 1; i < hex.length; i++) {
            // 转换出每一个代码点
            int data = Integer.parseInt(hex[i], 16);
            // 追加成string
            string.append((char) data);
        }

        return string.toString();
    }


    public static void main(String[] args) {
        System.out.println(string2Unicode("测试"));
        System.out.println(unicode2String("\\u77ed\\u4fe1\\u53d1\\u9001\\u5931\\u8d25"));

    }


}
